/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.jxtafileshare;

import net.jxta.exception.PeerGroupException;
import net.jxta.peergroup.PeerGroup;
import net.jxta.platform.NetworkConfigurator;
import net.jxta.platform.NetworkManager;

import java.text.MessageFormat;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import javax.security.cert.CertificateException;
import javax.swing.JOptionPane;
import net.jxta.discovery.DiscoveryService;
/**
 *
 * @author Danny
 */
public class NetworkStarter {

    public static final String Local_Peer_Name = "My Local Peer";
    public static final String Local_Network_Manager_Name =
            "My Local Network Manager";
    private NetworkManager TheNetworkManager;
    private NetworkConfigurator TheConfig;
    private PeerGroup TheNetPeerGroup;
    private net.jxta.platform.NetworkManager.ConfigMode mode;

    public NetworkStarter() {
        // Createing the Network Manager
        char answer;
        Scanner keyboard = new Scanner(System.in);
        System.out.println("Are you a rendezvous peer? y/n");
        answer = keyboard.nextLine().charAt(0);
        if(answer == 'y')
            mode = NetworkManager.ConfigMode.RENDEZVOUS;
        else
            mode = NetworkManager.ConfigMode.EDGE;
        try {
            System.out.println("Creating the Network Manager");
            TheNetworkManager = new NetworkManager(
                    mode, Local_Network_Manager_Name);
            System.out.println("Network Manager created");
        }catch(IOException ex) {
            ex.printStackTrace();
            System.exit(-1);
        }

        // Persisting it to make sure the Peer ID is not re-created
        // each time the Network Manager is instantiated
        TheNetworkManager.setConfigPersistent(true);
        System.out.println("PeerID: " + TheNetworkManager.getPeerID().toString());

        // Retrieving the Network Configurator
        System.out.println("Retrieving the Network Configurator");
        try {
            TheConfig = TheNetworkManager.getConfigurator();
        } catch(IOException e) {
            e.printStackTrace();
        }
        System.out.println("Network Configurator retrieved");

        // Does a local peer configuration exist?
        if(TheConfig.exists()) {
            System.out.println("Local configuration found");
            // We load it
            File LocalConfig = new File(TheConfig.getHome(), "PlatformConfig");
            try {
                System.out.println("Loading found configuration");
                TheConfig.load(LocalConfig.toURI());
                System.out.println("Configuration loaded");
            } catch(IOException ex) {
                ex.printStackTrace();
                System.exit(-1);
            } catch(CertificateException ex) {
                // An issue with the existing peer certificate has been encountered
                ex.printStackTrace();
                System.exit(-1);
            }
        } else {
            System.out.println("No local configuration found");
            TheConfig.setName(Local_Peer_Name);
            TheConfig.setPrincipal(getPrincipal());
            TheConfig.setPassword(getPassword());

            System.out.println("Principal: " + TheConfig.getPrincipal());
            System.out.println("Password: " + TheConfig.getPassword());

            try {
                System.out.println("Saving new configuration");
                TheConfig.save();
                System.out.println("New configuration saved successfully");
            } catch(IOException ex) {
                ex.printStackTrace();
                System.exit(-1);
            }
        }
    }

    private String getPrincipal() {
        return (String)JOptionPane.showInputDialog(
                null, "Enter principal", "Principal", JOptionPane.QUESTION_MESSAGE,
                null, null, "");
    }

    private String getPassword() {
        return (String)JOptionPane.showInputDialog(
                null, "Enter password", "Password", JOptionPane.QUESTION_MESSAGE,
                null, null, "");
    }

    public DiscoveryService getDiscoveryService() {
        return TheNetPeerGroup.getDiscoveryService();
    }

    public NetworkManager getNetworkManager() {
        return TheNetworkManager;
    }

    public net.jxta.platform.NetworkManager.ConfigMode getMode() {
        return mode;
    }

    public void startNetwork() {
        try {
            System.out.println("Starting JXTA");
            TheNetPeerGroup = TheNetworkManager.startNetwork();
            System.out.println("JXTA Started");

            System.out.println("Peer name: " +
                    TheNetPeerGroup.getPeerName());
            System.out.println("Peer Group name: " +
                    TheNetPeerGroup.getPeerGroupName());
            System.out.println("PeerGroup ID: " +
                    TheNetPeerGroup.getPeerID().toString());
        } catch(PeerGroupException ex) {
            // Cannot initialize peer group
            ex.printStackTrace();
            System.exit(-1);
        } catch(IOException ex) {
            ex.printStackTrace();
            System.exit(-1);
        }
    }

    public void SeekRendezvousConnection() {

        System.out.println("Waiting for a rendezvous connection for 25 seconds " +
                "(maximum)");
        boolean connected = TheNetworkManager.waitForRendezvousConnection(25000);
        System.out.println(MessageFormat.format("Connected: {0}", connected));
        TheNetworkManager.stopNetwork();
    }
}
